﻿using Grpc.Core;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using Windows.Admin.Contract;

namespace Windows.Identity.Api
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly User.UserClient _client;
        public ResourceOwnerPasswordValidator(User.UserClient client)
        {
            _client = client;
        }
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
                SignInRequest request = new()
                {
                    UserName = context.UserName,
                    Password = context.Password
                };
                SignInResponse response = await _client.SignInAsync(request);
                context.Result = new GrantValidationResult(response.Id.ToString(), OidcConstants.AuthenticationMethods.Password);
            }
            catch (RpcException ex)
            {
                context.Result = new GrantValidationResult(
                TokenRequestErrors.InvalidTarget,
                ex.Status.Detail);
            }
        }
    }
}
